package nix.demo2.web.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nix.commons.CommonUtils;
import nix.demo2.domain.User;
import nix.demo2.service.UserException;
import nix.demo2.service.UserService;

public class LoginServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		UserService userService = new UserService();
		// 表单数据封装至User对象
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);

		Map<String, String> errors = new HashMap<String, String>();

		if (form.getUsername() == null || form.getUsername().trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if (form.getUsername().length() < 2
				|| form.getUsername().length() > 16) {
			errors.put("username", "用户名长度必须在2-16位之间！");
		}

		if (form.getPassword() == null || form.getPassword().trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if (form.getPassword().length() < 3
				|| form.getPassword().length() > 16) {
			errors.put("password", "密码长度必须在3-16位之间！");
		}
		
		if (errors != null && errors.size() > 0) {
			request.setAttribute("errors", errors);
			// 数据回显
			request.setAttribute("user", form);
			request.getRequestDispatcher("/demo2/login.jsp").forward(
					request, response);
			return;
		}		

		try {
			User user = userService.login(form);

			Cookie cookie = new Cookie("cookie_username", URLEncoder.encode(
					form.getUsername(), "utf-8"));
			cookie.setMaxAge(60 * 60 * 24 * 7);
			cookie.setPath("/java-web-demo");
			response.addCookie(cookie);

			HttpSession session = request.getSession();
			session.setAttribute("session_user", user);

			response.sendRedirect(request.getContextPath() + "/demo2/index.jsp");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("user", form);
			request.getRequestDispatcher("/demo2/login.jsp").forward(request,
					response);
		}
	}

}
